import { pool } from '../src/config/database';
import { PasswordService } from '../src/services/password.service';
import dotenv from 'dotenv';

// 加载环境变量
dotenv.config();

async function initAdmin() {
  const adminUsername = process.env.ADMIN_USERNAME || 'admin';
  const adminPassword = process.env.ADMIN_PASSWORD || 'admin123';
  const adminName = process.env.ADMIN_NAME || '超级管理员';
  const adminEmail = process.env.ADMIN_EMAIL || 'admin@example.com';

  try {
    // 检查是否已存在超级管理员
    const [existingAdmin] = await pool.query(
      'SELECT * FROM users WHERE username = ? AND is_admin = 1',
      [adminUsername]
    );

    if (Array.isArray(existingAdmin) && existingAdmin.length > 0) {
      console.log('超级管理员账号已存在');
      process.exit(0);
    }

    // 加密密码
    const passwordService = PasswordService.getInstance();
    const hashedPassword = await passwordService.hashPassword(adminPassword);

    // 创建超级管理员账号
    await pool.query(
      `INSERT INTO users (username, password, name, email, is_admin, login_type, created_at, updated_at)
       VALUES (?, ?, ?, ?, 1, 'account', NOW(), NOW())`,
      [adminUsername, hashedPassword, adminName, adminEmail]
    );

    console.log('超级管理员账号创建成功');
    console.log(`用户名: ${adminUsername}`);
    console.log(`密码: ${adminPassword}`);
    process.exit(0);
  } catch (error) {
    console.error('创建超级管理员账号失败:', error);
    process.exit(1);
  }
}

// 运行初始化脚本
initAdmin(); 